package com.ruoyi.system.service.impl;

import com.ruoyi.system.domain.dto.SpuCrumbDto;
import com.ruoyi.system.domain.vo.CategoryVo;
import com.ruoyi.system.mapper.CrumbServiceMapper;
import com.ruoyi.system.service.ICrumbService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CrumbServiceImpl implements ICrumbService {
    @Autowired
    private CrumbServiceMapper crumbServiceMapper;

    /**
     * 根据categoryId获取面包屑导航
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<CategoryVo> getCrumbByCategoryId(Long categoryId) {
        CategoryVo node = crumbServiceMapper.selectById(categoryId);
        if (node == null) {
            return java.util.Collections.emptyList();
        }

        java.util.LinkedList<CategoryVo> breadcrumb = new java.util.LinkedList<>();
        // 自底向上查找所有父级，直到 level == 1 或 parentId 无效
        while (node != null) {
            // 头插，保证顺序为 父级 -> 子级 -> 当前
            breadcrumb.addFirst(node);
            Long level = node.getLevel();
            Long parentId = node.getParentId();
            if (level == null || level == 1 || parentId == null || parentId <= 0) {
                break;
            }
            node = crumbServiceMapper.selectById(parentId);
        }
        return breadcrumb;

    }

    /**
     * 根据spuId获取面包屑导航
     *
     * @param spuId
     */
    @Override
    public List<SpuCrumbDto> getCrumbBySpuId(Long spuId) {
        SpuCrumbDto first = crumbServiceMapper.getCrumbBySpuId(spuId);
        if (first == null) {
            return java.util.Collections.emptyList();
        }
        java.util.LinkedList<SpuCrumbDto> breadcrumb = new java.util.LinkedList<>();
        // 先加入当前SPU所在分类节点（包含spu信息）
        breadcrumb.addFirst(first);

        // 自底向上按分类父级继续补全
        Long level = first.getLevel();
        Long parentId = first.getParentId();
        while (!(level == null || level == 1 || parentId == null || parentId <= 0)) {
            com.ruoyi.system.domain.vo.CategoryVo parent = crumbServiceMapper.selectById(parentId);
            if (parent == null) {
                break;
            }
            SpuCrumbDto dto = new SpuCrumbDto();
            dto.setId(parent.getId());
            dto.setName(parent.getName());
            dto.setParentId(parent.getParentId());
            dto.setLevel(parent.getLevel());
            breadcrumb.addFirst(dto);

            level = parent.getLevel();
            parentId = parent.getParentId();
        }

        return breadcrumb;
    }
}
